package com.tb.ClassSchedule;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by guich on 2016/8/26.
 */
public class LoginActivity extends AppCompatActivity implements View.OnClickListener,CompoundButton.OnCheckedChangeListener{

    private EditText etNumber;
    private EditText etPassword;
    private EditText etCheckCode;
    private ImageView ivCheckCode;
    private CheckBox saveNumber;
    private CheckBox savePassword;
    private Button commitButton;

    private String number;
    private String password;
    private String checkCode;


    private Handler             handler;
    private AlertDialog.Builder builder;
    private Bitmap              bmCheckCode;


    public static final String HOST_URL   = "http://jwxt.hfnu.edu.cn";
    public static final String LOGIN_URL   = "/default2.aspx";
    public static final String CHECKCODE_URL   = "/CheckCode.aspx";
    public static String       RANDOM_URL = "";

    public static String mainBodyHtml = "";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activiy_login);
        initTitle();
        loadRes();
        initHandle();

    }

    private void initHandle() {

        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);

                if(msg.arg1 > 0 && msg.arg1 <= 9){
                    builder = new AlertDialog.Builder(LoginActivity.this);
                    builder.setTitle("提示");
                    builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {

                        }
                    });
                    switch (msg.arg1) {
                        case 1:
                            builder.setMessage("\n用户名不能为空");
                            break;
                        case 2:
                            builder.setMessage("\n密码或用户名错误");
                            break;
                        case 3:
                            builder.setMessage("\n密码不能为空");
                            break;
                        case 4:
                            builder.setMessage("\n验证码不能为空，如看不清请点击图片刷新");
                            break;
                        case 5:
                            builder.setMessage("\n用户名不存在或未按照要求参加教学活动");
                            break;
                        case 6:
                            etCheckCode.setText("");
                            builder.setMessage("\n验证码不正确");
                            break;
                        case 7:
                            builder.setMessage("\n获取验证码失败请检查网络设置");
                            break;
                        case 8:
                            builder.setMessage("\n恭喜！登陆成功");
                            break;
                        case 9:
                            builder.setMessage("\n获取课表成功，返回查看吧 ^_^");
                            break;
                    }
                    builder.show();
                }else{
                    switch (msg.arg1){
                        case 10:
                            Log.d("CheckCode","成功获取验证码");
                            ivCheckCode.setImageBitmap(bmCheckCode);
                            break;
                        case 11:
                            Log.d("Login","登陆成功");
                            doGetSrc();
                            break;
                    }

                }




            }
        };




    }

    private void loadRes() {
        etNumber = (EditText) findViewById(R.id.user_number);
        etPassword = (EditText) findViewById(R.id.password);
        etCheckCode = (EditText) findViewById(R.id.check_code);
        ivCheckCode = (ImageView) findViewById(R.id.check_code_view);
        ivCheckCode.setOnClickListener(this);
        saveNumber = (CheckBox) findViewById(R.id.save_number);
        savePassword = (CheckBox) findViewById(R.id.save_password);
        saveNumber.setOnCheckedChangeListener(this);
        savePassword.setOnCheckedChangeListener(this);
        commitButton = (Button) findViewById(R.id.commit_button);
        commitButton.setOnClickListener(this);

        doSharedPreference(false);

    }

    private void doSharedPreference(boolean isWrite) {
        if(isWrite){
            SharedPreferences.Editor editor = MainActivity.sharedPreferences.edit();
            editor.putBoolean("save_number",saveNumber.isChecked());
            editor.putBoolean("save_password",savePassword.isChecked());
            if(saveNumber.isChecked()){
                editor.putString("user_number",number);
            }else {
                editor.putString("user_number","");
            }
            if(savePassword.isChecked()){
                editor.putString("password",password);
            }else{
                editor.putString("password","");
            }
            editor.commit();
            editor.clear();
        }else{
            etNumber.setText(MainActivity.sharedPreferences.getString("user_number",""));
            etPassword.setText(MainActivity.sharedPreferences.getString("password",""));
            saveNumber.setChecked(MainActivity.sharedPreferences.getBoolean("save_number",false));
            savePassword.setChecked(MainActivity.sharedPreferences.getBoolean("save_password",false));
        }
    }

    private void initTitle() {
        //透明状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("登陆教务系统");
        setSupportActionBar(toolbar);
        //显示返回按钮
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            toolbar.setPadding(0,MainActivity.statusBarHeight,0,0);
        }
        toolbar.setBackgroundColor(MainActivity.sharedPreferences.getInt("color",MainActivity.DEFAULT_THEME));

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            //处理返回按钮
            onBackPressed();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onResume() {
        super.onResume();
        //获取随机码完获取验证码
        doGetRandomUrl();

    }

    private void doGetRandomUrl() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(HOST_URL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setInstanceFollowRedirects(false);

                    String location = connection.getHeaderField("Location");
                    Log.d("location",location);
                    RANDOM_URL = location.substring(0,location.indexOf(LOGIN_URL));
                    Log.d("截取了",RANDOM_URL);

                    doGetCheckCode();

                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

            }
        }).start();

    }

    private void doGetCheckCode() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;
                try {
                    URL url = new URL(HOST_URL + RANDOM_URL + CHECKCODE_URL);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    InputStream in = connection.getInputStream();

                    bmCheckCode = BitmapFactory.decodeStream(in);


                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }

                Message msg = new Message();
                if (bmCheckCode == null){
                    msg.arg1 = 7;
                    handler.sendMessage(msg);
                }else{
                    msg.arg1 = 10;
                    handler.sendMessage(msg);
                }

            }
        }).start();

    }


    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.commit_button:
                number = etNumber.getText().toString();
                password = etPassword.getText().toString();
                checkCode = etCheckCode.getText().toString();

                doSharedPreference(true);

                doLogin();
                break;
            case R.id.check_code_view:
                Log.d("CheckCode","ib_refresh开始获取");
                doGetCheckCode();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if(getIntent().getIntExtra("function",0) == R.id.import_course_button){
            MainActivity.main.draw();
        }
        super.onDestroy();
    }

    private void doGetSrc() {

        switch (getIntent().getIntExtra("function", 0)) {
            case R.id.import_course_button:
                LessonParser.parse(mainBodyHtml,number);
                Message message = new Message();
                message.arg1 = 9;
                handler.sendMessage(message);
                break;

            default:
                message = new Message();
                message.arg1 = 8;
                handler.sendMessage(message);

        }


    }




    private void doLogin() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HttpURLConnection connection = null;

                //获得个人主界面的HTML
                try {

                    URL url = new URL(HOST_URL + RANDOM_URL + LOGIN_URL);

                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("POST");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);


                    DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                    out.writeBytes("__VIEWSTATE=dDwyODE2NTM0OTg7Oz4J1M0E12oUlEr84Lqk6/XAPSioRg==" +
                            "&hidsc=" +
                            "&lbLanguage=" +
                            "&Button1=" +
                            "&hidPdrs=" +
                            "&txtUserName=" + number +
                            "&TextBox2=" + password +
                            "&txtSecretCode=" + checkCode +
                            "&RadioButtonList1=学生");

                    InputStream in = connection.getInputStream();
                    Log.d("code", connection.getURL().toString());


                    BufferedReader reader = new BufferedReader(new
                            InputStreamReader(in, Charset.forName("gb2312")));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }

                    mainBodyHtml = response.toString();
                    IsLoginSuccessful(mainBodyHtml);

                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (connection != null) {
                        connection.disconnect();
                    }
                }
            }
        }).start();
    }

    private void IsLoginSuccessful(String loginResult) {
        Log.d("loginResult",loginResult);
        Document doc     = Jsoup.parse(loginResult);
        Elements alert   = doc.select("script[language]");
        Elements success = doc.select("span[id=Label3]");

        Message msg = new Message();
        //先判断是否登录成功，若成功直接退出
        for (Element link : success) {
            //获取所要查询的URL,这里对应地址按钮的名字叫成绩查询
            if (link.text().equals("欢迎您：")) {
                Log.d("CheckCode","登录成功");
                doGetCheckCode();
                msg.arg1 = 11;
                handler.sendMessage(msg);
                return;
            }
        }

        for (Element link : alert) {
            //刷新验证码
            Log.d("Verification","登陆失败开始获取");
            doGetCheckCode();

            //获取错误信息
            if (link.data().contains("用户名不能为空")) {
                msg.arg1 = 1;
                handler.sendMessage(msg);
            } else if (link.data().contains("密码错误")) {
                msg.arg1 = 2;
                handler.sendMessage(msg);
            } else if (link.data().contains("密码不能为空")) {
                msg.arg1 = 3;
                handler.sendMessage(msg);
            } else if (link.data().contains("验证码不能为空，如看不清请刷新")) {
                msg.arg1 = 4;
                handler.sendMessage(msg);
            } else if (link.data().contains("用户名不存在")) {
                msg.arg1 = 5;
                handler.sendMessage(msg);
            }else if (link.data().contains("验证码不正确")) {
                msg.arg1 = 6;
                handler.sendMessage(msg);
            }
        }

    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        if(compoundButton.getId() == R.id.save_number && !b){
            savePassword.setChecked(false);
        }else if(compoundButton.getId() == R.id.save_password && b){
            saveNumber.setChecked(true);
        }
    }
}
